package metadata;

import java.util.*;

public class Table {
	
	//private vars
	private String 							name		= "";
	private Key								primaryKey	= null;
	private Map<String, Column>				columns 	= null;
	private Map<String, Key>				keys		= null;
	private Map<String, ForeignKey> 		foreignKeys	= null;
	
	//constructors
	public Table(String name) {
		this.name 	= name;
		
		columns		= new HashMap<String, Column>();
		keys 		= new HashMap<String, Key>();
		foreignKeys	= new HashMap<String, ForeignKey>();
	}
	
	
	//simple getters
	public String getName() 	{ return name; 			}
	public Key getPrimaryKey() 	{ return primaryKey; 	}
	
	
	//simple setters
	public void setName(String name) 			{ this.name = name; 			}
	public void setPrimaryKey(Key primaryKey) 	{ this.primaryKey = primaryKey; }
	
	
	//complex getters
	public boolean hasColumn(String columnName) {
		return columns.containsKey(columnName);
	}
	
	public boolean hasKey(String keyName) {
		return keys.containsKey(keyName);
	}
	
	public boolean hasForeignKey(String foreignKeyName) {
		return foreignKeys.containsKey(foreignKeyName);
	}
	
	public Column getColumn(String columnName) {
		return columns.get(columnName);
	}
	
	public Key getKey(String keyName) {
		return keys.get(keyName);
	}
	
	public ForeignKey getForeignKey(String foreignKeyName) {
		return foreignKeys.get(foreignKeyName);
	}
	
	public Set<String> getAllColumnNames() {
		return new HashSet<String>(columns.keySet());
	}
	
	public Set<String> getAllKeyNames() {
		return new HashSet<String>(keys.keySet());
	}
	
	public Set<String> getAllForeignKeyNames() {
		return new HashSet<String>(foreignKeys.keySet());
	}
	
	//complex setters
	public void addColumn(Column column) {
		columns.put(column.getName(), column);
	}
	
	public void addKey(Key key) {
		keys.put(key.getName(), key);
	}
	
	public void addForeignKey(ForeignKey foreignKey) {
		foreignKeys.put(foreignKey.getName(), foreignKey);
	}
	
	public void removeColumn(String columnName) {
		columns.remove(columnName);
	}
	
	public void removeKey(String keyName) {
		keys.remove(keyName);
	}

	public void removeForeignKey(String foreignKeyName) {
		foreignKeys.remove(foreignKeyName);
	}
	
	public void refreshColumnName(String oldColumnName) {
		Column column = columns.get(oldColumnName);
		if(!column.getName().equals(oldColumnName)) { 	//If the column names are equal, the put() call makes no change and remove()
			columns.put(column.getName(), column);		//would get rid of the column entirely. The if() prevents this, and now
			columns.remove(oldColumnName);				//the column never leaves the map as it is put() before being removed().
		}												//And it is important it never leaves the map, in case the app suddenly stops
	}
}
